//
//  ViewController.m
//  断点续传(断点下载)
//
//  Created by on 16/2/24.
//  Copyright © 2016年 .liufy. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"

//QQ下载地址
#define QQ_URL @"http://dldir1.qq.com/qqfile/QQforMac/QQ_V4.1.1.dmg"

@interface ViewController ()
//显示百分比的标签
@property (weak, nonatomic) IBOutlet UILabel *percentLabel;
//进度条
@property (weak, nonatomic) IBOutlet UIProgressView *percentProgress;
//下载任务
@property (nonatomic,strong)NSURLSessionDownloadTask *downLoadTask;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

#pragma mark- 断点下载相关
//下载数据
//resumeData 未下载完成的二进制文件
-(void)requestWith:(NSData *)resumeData{
    
     AFHTTPSessionManager *sessionManger = [AFHTTPSessionManager new];
    
    if (resumeData) {
        //非第一次下载
        self.downLoadTask = [sessionManger downloadTaskWithResumeData:resumeData progress:^(NSProgress * _Nonnull downloadProgress) {
            
            NSLog(@"下载的进度为%f",(CGFloat)(downloadProgress.completedUnitCount) / downloadProgress.totalUnitCount);
            //回到主线程刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //改变下载显示百分比
                self.percentLabel.text = [NSString stringWithFormat:@"%.2f%%",((CGFloat)(downloadProgress.completedUnitCount) / downloadProgress.totalUnitCount) * 100];
                //改变下载进度
                self.percentProgress.progress = (CGFloat)(downloadProgress.completedUnitCount) / downloadProgress.totalUnitCount;
            });
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            //targetPath表示临时文件存放路径
            //提供文件最终存储路径，以便把临时文件剪切到最终存储路径
            return [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingString:@"/Documents/qq.dmg"]];
            
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            //下载完成之后会回调此方法
            
            if (error) {
                NSLog(@"error = %@",[error description]);
            }else{
                //下载成功，filePath就是文件最终存储路径
                NSLog(@"filePath = %@",filePath);
            }
        }];
        
    }else{
        
        //第一次下载
        self.downLoadTask = [sessionManger downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:QQ_URL]] progress:^(NSProgress * _Nonnull downloadProgress) {
            //downloadProgress 下载进度
            NSLog(@"下载的进度为%f",(CGFloat)(downloadProgress.completedUnitCount) / downloadProgress.totalUnitCount);
            
            //回到主线程刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //改变下载显示百分比
                self.percentLabel.text = [NSString stringWithFormat:@"%.2f%%",((CGFloat)(downloadProgress.completedUnitCount) / downloadProgress.totalUnitCount) * 100];
                //改变下载进度
                self.percentProgress.progress = (CGFloat)(downloadProgress.completedUnitCount) / downloadProgress.totalUnitCount;
            });
            
            
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            
            //targetPath表示临时文件存放路径
            //提供文件最终存储路径，以便把临时文件剪切到最终存储路径
            return [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingString:@"/Documents/qq.dmg"]];
            
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            //下载完成之后会回调此方法
            
            if (error) {
                NSLog(@"error = %@",[error description]);
            }else{
                //下载成功，filePath就是文件最终存储路径
                NSLog(@"filePath = %@",filePath);
            }
        }];
    }
    
    //执行下载任务
    [self.downLoadTask resume];
}


#pragma mark- 各类触发事件
//开始
- (IBAction)startAction:(id)sender {
    
    //如果已经在下载中，则防止用户狂点击下载按钮
    if (self.downLoadTask) {
        return;
    }
    
    //开启下载
    [self requestWith:[[NSUserDefaults standardUserDefaults] objectForKey:@"resumeData"]];
}

//取消
- (IBAction)cancelAction:(id)sender {
    //取消当前的下载任务
    [self.downLoadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        //把下载完成的二进制文件保存到本地
        [[NSUserDefaults standardUserDefaults] setObject:resumeData forKey:@"resumeData"];
        //保存
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
    
    //置空
    self.downLoadTask = nil;
}

@end
